package message.action;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;

import message.bean.Message;
import message.factory.MessageFactory;
import message.service.MessageService;

import com.opensymphony.xwork2.ActionSupport;
public class MessageAction extends ActionSupport implements SessionAware{
	private Message Message=new Message();
	private List<Message> Messagelist=new ArrayList<Message>();
	private Map session;
	private int pagenow;
	
	public int getPagenow(){
		return pagenow;
	}
    public  void setPagenow(int pagenow){
    	this.pagenow=pagenow;
    }
	public void setMessage(Message Messagebean){
		this.Message=Messagebean;
	}
	
	public Message getMessage(){
		return Message;
	}
	
	public List<Message> getMessagelist(){
		return Messagelist;
	}
	
	public void setMessagelist(List<Message> Messagelist){
		this.Messagelist=Messagelist;
	}
	
	public Map getSession() {
		return session;
	}

	@Override
	public void setSession(Map session) {
		this.session = session;
	}
	
	
	
	public String deleteMessage() throws Exception {
		MessageService Messageservice =MessageFactory.getInstance().creatMessageService();
		if (!Messageservice.DeleteMessage(Message)) {
			this.addActionError("deleteMessage error");
			return INPUT;
		} else {
			this.addActionError("deleteMessage error");
			return SUCCESS;
		}
	}
	
	public String addMessage() throws Exception {	
		MessageService Messageservice=MessageFactory.getInstance().creatMessageService();
		if (Message.getContent().trim().equalsIgnoreCase("")) {
			this.addActionError("addMessage error");
			return INPUT;
		}
		if(!Messageservice.AddMessage(Message)){
			System.out.println("called addmessage");
			this.addActionError("addMessage error");
			return INPUT;
		}
		this.addActionError("addMessage error");
		return SUCCESS;
	}

	 public String showallMessage() throws Exception{
		 MessageService Messageservice=MessageFactory.getInstance().creatMessageService();
		 Messagelist=Messageservice.ShowAllMessage(getPagenow(),6);
		 if(getPagenow()==0){
			 int total=Messageservice.CountAllMessage();
			 int page=0;
			 do {
					total = total - 6;
					page++;
				} while (total > 0);
				this.session.put("messagetotalpage", page);
		 }
		 if(Messagelist.size()==0){
			 this.addActionError("showallMessage error");
			return INPUT;
		 }else{
			 return  SUCCESS; 
		 }
	 }
	 
	 public String showoneMessage() throws Exception{
			MessageService MessageService =MessageFactory.getInstance().creatMessageService();
			Message= MessageService.ShowoneMessage(Message);
			
			if (Message == null) {
				this.addActionError("Error!");
				return INPUT;
			} else {
				//this.session.put("Message", Message);
				return SUCCESS;
			}
		}
	 }
